﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace EcodexIntegrationSample.Controllers
{
    class frmCancelarTimbradoController
    {
        private View.IfrmCancelarTimbrado _view;
        private Random _random;


        public frmCancelarTimbradoController(View.IfrmCancelarTimbrado view)
        {
            _view = view;
            _view.onCancelarTimbrado += _view_onCancelarTimbrado;
            _random = new Random();
        }

        void _view_onCancelarTimbrado(object sender, EventArgs e)
        {
            string rfc = _view.RFCEmisor;
            string UUID = _view.UUID;
            Int64 transactionID = _random.Next();            
            string token = string.Empty;
            string Error;
            Utils.Utilerias Util = new Utils.Utilerias(_view);
            Error = Util.CreateToken(rfc, transactionID, ref token);
            if (!string.IsNullOrEmpty(Error))
            {
                _view.ShowUnknownError(Error);
                return;
            }
            try
            {
                using (var srvTimbrado = new SrvTimbrado.TimbradoClient())
                {
                    var respuesta = srvTimbrado.CancelaTimbrado(rfc, token, ref transactionID, UUID);
                    _view.Resultado = (respuesta ? "Cancelado" : "No cancelado");

                }
            }
            catch (FaultException<SrvTimbrado.FallaServicio> serviceFault)
            {
                using (var errorForm = new Forms.Error(TranslateFault.ToServiceError(serviceFault.Detail)))
                {
                    errorForm.ShowDialog();
                }
            }
            catch (FaultException<SrvTimbrado.FallaSesion> sessionFauld)
            {
                using (var errorForm = new Forms.Error(TranslateFault.ToSessionError(sessionFauld.Detail)))
                {
                    errorForm.ShowDialog();
                }
            }
            #region Timbrado service exceptions
            catch (FaultException<SrvTimbrado.FallaValidacion> validationFault)
            {
                using (var errorForm = new Forms.Error(TranslateFault.ToValidationError(validationFault.Detail)))
                {
                    errorForm.ShowDialog();
                }
            }     
            #endregion
            catch (TimeoutException)
            {
                _view.ShowUnknownError("Error de tiempo de espera del servicio");
            }
            catch (Exception ex)
            {
                _view.ShowUnknownError(ex.Message);
            }
        }
    }
}
